package com.shop.cereshop.app.dl.logic.service.Impl;


import com.alibaba.fastjson.JSONObject;
import com.shop.cereshop.app.dao.dl.CereShopDestroyTicketsDao;
import com.shop.cereshop.app.dao.order.CereOrderProductDAO;
import com.shop.cereshop.app.dao.order.CereShopOrderDAO;
import com.shop.cereshop.app.dl.logic.domain.CereShopDestroyTickets;
import com.shop.cereshop.app.dl.logic.domian.*;
import com.shop.cereshop.app.dl.logic.utils.JsonUtils;
import com.shop.cereshop.commons.domain.order.CereOrderProduct;
import com.shop.cereshop.commons.domain.order.CereShopOrder;
import com.shop.cereshop.commons.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @description 远程接口调用
 * @Author YF
 * @Date 日期:2021/5/20 时间:14:12
 */
@Service
public class SendPostImpl {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${Dl_Data.version}")
    private String version;
    @Value("${Dl_Data.userId}")
    private String user_id;
    @Value("${Dl_Data.name}")
    private String user_key;
    @Value("${Dl_Data.month}")
    private Long month;

    @Autowired
    private CereShopOrderDAO cereShopOrderDAO;
    @Autowired
    private CereOrderProductDAO cereOrderProductDAO;
    @Autowired
    private CereShopDestroyTicketsDao cereShopDestroyTicketsDao;

    /**
     * @param
     * @description:获取产品信息
     * @return:
     * @author:作者:YF
     * @time:日期:2021/5/19 时间:13:53
     */
    public String GetProductInfo(Integer pageIndex,Integer pageSize,String productNo,String sceneryNo,String productType) {
        JSONObject json = new JSONObject();
        //定义返回值(第一个未解密，第二个已解密)
//        final String[] data = new String[1];
//        final String[] decryptData = new String[1];
        String result = new String();
        //.定义方法
        String method = "GetProductInfo";
        //定义时间
        long st = System.currentTimeMillis() / 1000;
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            json.put("pageIndex",pageIndex);
            json.put("pageSize",pageSize);
            json.put("productNo",productNo);
            json.put("sceneryNo",sceneryNo);
            json.put("productType",productType);
            encrypt = encrypt("{" + "pageIndex:"+json.get("pageIndex")+","+"pageSize:"+json.get("pageSize")+","+"productNo:"+json.get("productNo")+","
                    +"sceneryNo:"+json.get("sceneryNo")+","
                    +"productType:"+json.get("productType")+ "}", user_key);
            System.out.println(decrypt(encrypt,user_key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = getMD5(user_id + method + st + version + encrypt + user_key);
        //.封装JSON格式数据
        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod(method);
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        System.out.println(json);
        //.请求地址URL
        String url = "http://service.zhuxiaoke.cn/Tongcheng/ProcessRequest/";
        //远程调用
        String resultInfo = restTemplate.postForObject(url, json, String.class);

        try {
            //解密
            result = decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
            System.out.println("数据："+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
        //.创建异步远程调用Client
//        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
//        httpclient.start();
//        final CountDownLatch latch = new CountDownLatch(1);
//        final HttpPost post = new HttpPost(url);
//        try {
//            post.setEntity(new StringEntity(json.toString()));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        //.发送异步请求
//        httpclient.execute(post, new FutureCallback<HttpResponse>() {
//            @Override
//            public void completed(final HttpResponse response) {
//                latch.countDown();
//                System.out.println(" callback thread id is : " + Thread.currentThread().getId());
//                System.out.println(post.getRequestLine() + "->" + response.getStatusLine());
//                try {
//                    data[0] = EntityUtils.toString(response.getEntity(), "UTF-8");
//                    System.out.println(" response content is : " + data[0]);
//                    decryptData[0] = decrypt((String) JsonUtils.toMap(data[0]).get("responseBody"), "xmxm1231");
//                    System.out.println(decryptData[0]);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//
//            @Override
//            public void failed(final Exception ex) {
//                latch.countDown();
//                System.out.println(post.getRequestLine() + "->" + ex);
//                System.out.println(" 发送异步请求失败: " + Thread.currentThread().getId());
//            }
//
//            @Override
//            public void cancelled() {
//                latch.countDown();
//                System.out.println(post.getRequestLine() + " cancelled");
//                System.out.println(" 取消异步请求 : " + Thread.currentThread().getId());
//            }
//        });
//
//        try {
//            latch.await();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        try {
//            httpclient.close();
//        } catch (IOException ignore) {
//
//        }
//        System.out.println("最终数据："+decryptData[0]);
//        return decryptData[0];
    }


    /**
     * @param
     * @description: 产品价格日历
     * @return:
     * @author:作者:YF
     * @time:日期:2021/5/20 时间:15:27
     */
    public String GetCalenderPrice(Integer productNo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //.定义当前时间
        Long startTime = System.currentTimeMillis();
        //.定义一个月时间
        Long endTime = startTime + month;
        String startTimeS = simpleDateFormat.format(new Date(Long.parseLong(String.valueOf(startTime))));
        String endTimeS = simpleDateFormat.format(new Date(Long.parseLong(String.valueOf(endTime))));
        JSONObject json = new JSONObject();
        //.返回参数
        String result = new String();
        //.定义时间
        long st = System.currentTimeMillis() / 1000;
        //.定义方法
        String method = "GetCalenderPrice";
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            json.put("productNo",productNo);
            json.put("startTime",startTimeS);
            json.put("endTime",endTimeS);

            encrypt = encrypt("{" + "productNo:"+json.get("productNo")+","+"startTime:"+"\""+json.get("startTime")+"\""+","+
                    "endTime:"+"\""+json.get("endTime")+"\""+ "}", user_key);
            System.out.println(decrypt(encrypt,user_key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = getMD5(user_id + method + st + version + encrypt + user_key);
        //.封装JSON格式数据

        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod(method);
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        //.请求地址URL
        String url = "http://service.zhuxiaoke.cn/Tongcheng/ProcessRequest/";
        //.发送请求
        String resultInfo = restTemplate.postForObject(url, json, String.class);
        System.out.println(resultInfo);
        try {
            result = decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }


    /**
     * @param
     * @description:订单接口(下订单)
     * @author:作者:YF
     * @time:日期:2021/5/20 时间:16:36
     */
    public ResultYf CreateOrder(String orderSerialId, String productNo, Integer payType, Integer tickets, Long price, Long contractPrice, String bookName, String bookMobile,
                              String idCard, String travelDate, String departDate, String bookBeginTime, String bookEndTime, List<VisitPerson> visitPerson, Address address) {
        JSONObject json = new JSONObject();
        StringBuffer buffer = new StringBuffer("");
        buffer.append("{");
        buffer.append("orderSerialId:\""+orderSerialId+"\",");
        buffer.append("productNo:\""+productNo+"\",");
        buffer.append("payType:"+payType+",");
        buffer.append("tickets:"+tickets+",");
        buffer.append("price:"+price+",");
        buffer.append("contractPrice:"+contractPrice+",");
        buffer.append("bookName:\""+bookName+"\",");
        buffer.append("bookMobile:\""+bookMobile+"\",");
        buffer.append("idCard:\""+idCard+"\",");
        buffer.append("travelDate:\""+travelDate+"\",");
        buffer.append("departDate:\""+departDate+"\",");
        buffer.append("bookBeginTime:\""+bookBeginTime+"\",");
        buffer.append("bookEndTime:\""+bookEndTime+"\",");
//        buffer.append("visitPerson:[");
//        int size = visitPerson.size();
//        int i = 0;
//        for (VisitPerson person : visitPerson) {
//            buffer.append("{");
//            buffer.append("name:\""+person.getName()+"\",");
//            buffer.append("mobile:\""+person.getMobile()+"\",");
//            buffer.append("idCard:\""+person.getIdCard()+"\"");
//            if (i++<size-1){
//                buffer.append("},");
//            }else {
//                buffer.append("}");
//            }
//        }
//        buffer.append("],");
//        buffer.append("address:"+"{");
//        buffer.append("name:\""+address.getName()+"\",");
//        buffer.append("mobile:\""+address.getMobile()+"\",");
//        buffer.append("address:\""+address.getAddress()+"\"}");
        buffer.append("visitPerson:"+visitPerson+",");
        buffer.append("address:"+address);
        buffer.append("}");
        String data = buffer.toString();
        //.返回参数
        String result = new String();
        ResultYf resultYf = new ResultYf();
        //.定义时间
        long st = System.currentTimeMillis() / 1000;
        //.定义方法
        String method = "CreateOrder";
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            encrypt = encrypt(data, user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = getMD5(user_id + method + st + version + encrypt + user_key);
        //.封装JSON格式数据
        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod(method);
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        //.请求地址URL
        String url = "http://service.zhuxiaoke.cn/Tongcheng/ProcessRequest/";
        //.发送请求
        String resultInfo = restTemplate.postForObject(url, json, String.class);
        System.out.println(resultInfo);
        try {
            result = decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
            resultYf.setMessage(result);
            JSONObject responseHead = (JSONObject) JsonUtils.toMap(resultInfo).get("responseHead");
            String resCode = (String) responseHead.get("res_code");
            if (resCode.equals("1000")){
                resultYf.setResult(true);
            }else {
                resultYf.setResult(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultYf;
    }


    /**
     * @param
     * @description:查询接口
     * @return:
     * @author:作者:YF
     * @time:日期:2021/5/22 时间:15:09
     */
    public String QueryOrder(String orderSerialId,String partnerOrderId) {
        JSONObject json = new JSONObject();
        //.返回参数
        String result = new String();
        //.定义时间
        long st = System.currentTimeMillis() / 1000;
        //.定义方法
        String method = "QueryOrder";
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            json.put("orderSerialId",orderSerialId);
            json.put("partnerOrderId",partnerOrderId);
            encrypt = encrypt("{"+"orderSerialId:"+"\""+json.get("orderSerialId")+"\","+
                    "partnerOrderId:"+"\""+json.get("partnerOrderId")+"\""+"}", user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = getMD5(user_id + method + st + version + encrypt + user_key);
        //.封装JSON格式数据
        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod(method);
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        //.请求地址URL
        String url = "http://service.zhuxiaoke.cn/Tongcheng/ProcessRequest/";
        //.发送请求
        String resultInfo = restTemplate.postForObject(url, json, String.class);
        System.out.println(resultInfo);
        try {
            result = decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;


    }


    /**
     * @description:退单接口（平台提供）
     * @param
     * @return:
     * @author:作者:YF
     * @time:日期:2021/5/22 时间:15:26
     */
    public String CancelOrder(String orderSerialId,String partnerOrderId,String reason,Integer tickets){
        JSONObject json = new JSONObject();
        //.返回参数
        String result = new String();
        //.定义时间
        long st = System.currentTimeMillis() / 1000;
        //.定义方法
        String method = "CancelOrder";
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            json.put("orderSerialId",orderSerialId);
            json.put("partnerOrderId",partnerOrderId);
            json.put("reason",reason);
            json.put("tickets",tickets);
            encrypt = encrypt("{"+"orderSerialId:\""+json.get("orderSerialId")+"\","
                    +"partnerOrderId:\""+json.get("partnerOrderId")+"\","
                    +"reason:\""+json.get("reason")+"\","
                    +"tickets:"+json.get("tickets")
                    +"}", user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = getMD5(user_id + method + st + version + encrypt + user_key);
        //.封装JSON格式数据
        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod(method);
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        //.请求地址URL
        String url = "http://service.zhuxiaoke.cn/Tongcheng/ProcessRequest/";
        //.发送请求
        String resultInfo = restTemplate.postForObject(url, json, String.class);
        System.out.println(resultInfo);
        try {
            result = decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;

    }



    /**
     *
     * @description:订单核销接口（平台提供）
     * @param
     * @return:
     *
     * @author:作者:YF
     * @time:日期:2021/5/22  时间:16:39
     */
    public String CheckTicket(String barcodeNo,Integer checkCount){
        JSONObject json = new JSONObject();
        //.返回参数
        String result = new String();
        //.定义时间
        long st = System.currentTimeMillis() / 1000;
        //.定义方法
        String method = "CheckTicket";
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            json.put("barcodeNo",barcodeNo);
            json.put("checkCount",checkCount);
            encrypt = encrypt("{"+"barcodeNo:\""+json.get("barcodeNo")+"\","
                    +"checkCount:"+json.get("checkCount")
                    +"}", user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = getMD5(user_id + method + st + version + encrypt + user_key);
        //.封装JSON格式数据
        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod(method);
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        //.请求地址URL
        String url = "http://service.zhuxiaoke.cn/Tongcheng/ProcessRequest/";
        //.发送请求
        String resultInfo = restTemplate.postForObject(url, json, String.class);
        System.out.println(resultInfo);
        try {
            result = decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }



    /**
     * @param
     * @description:校验订单接口
     * @return:
     * @author:作者:YF
     * @time:日期:2021/5/19 时间:13:53
     */
    public JSONObject VerifyOrder(OrderValidation validation) {
        JSONObject json = new JSONObject();
        StringBuffer buffer = new StringBuffer("");
        buffer.append("{");
        buffer.append("orderSerialId:\""+validation.getOrderSerialId()+"\",");
        buffer.append("productNo:\""+validation.getProductNo()+"\",");
        buffer.append("payType:"+validation.getPayType()+",");
        buffer.append("tickets:"+validation.getTickets()+",");
        buffer.append("price:"+validation.getPrice()+",");
        buffer.append("contractPrice:"+validation.getContractPrice()+",");
        buffer.append("bookName:\""+validation.getBookName()+"\",");
        buffer.append("bookMobile:\""+validation.getBookMobile()+"\",");
        buffer.append("idCard:\""+validation.getIdCard()+"\",");
        buffer.append("travelDate:\""+validation.getTravelDate()+"\",");
        buffer.append("departDate:\""+validation.getDepartDate()+"\",");
        buffer.append("bookBeginTime:\""+validation.getBookBeginTime()+"\",");
        buffer.append("bookEndTime:\""+validation.getBookEndTime()+"\",");
        buffer.append("visitPerson:"+validation.getVisitPerson()+",");
        buffer.append("address:"+validation.getAddress());
        buffer.append("}");
        String data = buffer.toString();
        System.out.println(data);
        //.返回参数
        String result = new String();
        JSONObject responseHead = new JSONObject();
        //.定义时间
        long st = System.currentTimeMillis() / 1000;
        //.定义方法
        String method = "VerifyOrder";
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            encrypt = encrypt(data, user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = getMD5(user_id + method + st + version + encrypt + user_key);
        //.封装JSON格式数据
        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod(method);
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        System.out.println("封装的JSON数据是："+json);
        //.请求地址URL
        String url = "http://service.zhuxiaoke.cn/Tongcheng/ProcessRequest/";
        //.发送请求
        String resultInfo = restTemplate.postForObject(url, json, String.class);
        System.out.println("校验响应数据为："+resultInfo);
        try {
            result = decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
            responseHead = (JSONObject) JsonUtils.toMap(resultInfo).get("responseHead");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return responseHead;
    }
    /**
     *
     * @description:所有接口调用
     * @param
     * @return:
     *
     * @author:作者:YF
     * @time:日期:2021/5/24  时间:10:18
     */
    public String sendPostAll(String method,String data){
        //.返回参数
        String result = new String();
        //.定义时间
        long st = System.currentTimeMillis() / 1000;
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            encrypt = encrypt(data, user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = getMD5(user_id + method + st + version + encrypt + user_key);
        //.封装JSON格式数据
        JSONObject json = new JSONObject();
        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod(method);
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        //.请求地址URL
        String url = "http://service.zhuxiaoke.cn/Tongcheng/ProcessRequest/";
        //.发送请求
        String resultInfo = restTemplate.postForObject(url, json, String.class);
        System.out.println(resultInfo);
        try {
            result = decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }


    /**
     * @param
     * @description:订单核销通知接口
     * @return:
     * @author:作者:YF
     * @time:日期:2021/6/24 时间:16:30
     */
    public synchronized Result ConsumeNotice(String request) {
        StringBuilder buffer = new StringBuilder();
        String requestBody = (String) JsonUtils.toMap(request).get("requestBody");
        JSONObject requestHead = (JSONObject) JsonUtils.toMap(request).get("requestHead");
        long millis = System.currentTimeMillis() / 1000;
        //1，获取user_id
        String userId = (String) requestHead.get("user_id");
        //2.获取method
        String method = (String) requestHead.get("method");
        //3.获取timestamp
        Integer timestamp = (Integer) requestHead.get("timestamp");
        //4.获取version
        String versions = (String) requestHead.get("version");
        //5.获取sign
        String sign = (String) requestHead.get("sign");
        //6.获取requestBody
        String decrypt = null;
        Result result = new Result();
        //1.首先可以拿到几个加密参数就是user_id，method，timestamp，version+requestBody里的des加密后的参数,去解析MD5的参数,判断是否正确
        String mysign = getMD5(userId + method + timestamp + versions + requestBody + user_key);
        //.如果参数不等于则返回错误信息
        if (userId.equals(user_id) && "ConsumeNotice".equals(method) && timestamp != null && versions.equals(version) && sign.equals(mysign)) {
            //2.拿requestBody去解码成所需的参数
            try {
                decrypt = decrypt(requestBody, user_key);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String orderSerialId = (String) JsonUtils.toMap(decrypt).get("orderSerialId");
            System.out.println(orderSerialId);
            String partnerOrderId = (String) JsonUtils.toMap(decrypt).get("partnerOrderId");
            System.out.println(partnerOrderId);
            Integer tickets = (Integer) JsonUtils.toMap(decrypt).get("tickets");
            System.out.println(tickets);
            String consumeDate = (String) JsonUtils.toMap(decrypt).get("consumeDate");
            System.out.println(consumeDate);
            Integer totalCheckCount = (Integer) JsonUtils.toMap(decrypt).get("totalCheckCount");
            System.out.println(totalCheckCount);
            //去数据库查询是否有该票务
            Integer orderForMid = cereShopOrderDAO.getByForMid(orderSerialId);
            //...用orderSerialId去查询orderId
            CereShopOrder cereShopOrder = cereShopOrderDAO.getShopOrderByForMid(orderSerialId);
            ResponseHead responseHead = new ResponseHead();
            if (orderForMid != null && partnerOrderId != null && tickets != null && consumeDate != null && cereShopOrder!=null && totalCheckCount != null) {
                CereOrderProduct cereOrderProduct = cereOrderProductDAO.selectByOrderId(cereShopOrder.getOrderId());
                //...取出数量做比较
//                Integer number = cereOrderProduct.getAvailable();

                //减少数量, 这里时数量为一才能进来的， 所以直接设置为0
                cereOrderProductDAO.updateNumberBytickets(0, cereShopOrder.getOrderId());

                //...修改订单状态为已完成
                cereShopOrderDAO.updateByOrderForMid(orderSerialId);
                responseHead.setRes_code("1000");
                responseHead.setRes_msg("操作成功");
                responseHead.setTimestamp(millis);
                result.setResponseHead(responseHead);
                buffer.append("{");
                buffer.append("responseHead:{");
                buffer.append("res_code:").append(responseHead.getRes_code()).append(",");
                buffer.append("res_msg:").append(responseHead.getRes_msg()).append(",");
                buffer.append("timestamp:").append(responseHead.getTimestamp()).append("}");
                buffer.append("}");
                String toString = buffer.toString();
                try {
                    String message = encrypt(toString, user_key);
                    result.setResponseBody(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }


                //核销完成后添加记录
                //添加数据
                //记录的实体类
                CereShopDestroyTickets cereShopDestroyTickets = new CereShopDestroyTickets();
                cereShopDestroyTickets.setCreateTime(TimeUtils.yyMMddHHmmss());
                cereShopDestroyTickets.setCounsumeDate(consumeDate);
                cereShopDestroyTickets.setOrderSerialld(orderSerialId);
                cereShopDestroyTickets.setTotalCheckCount(totalCheckCount);
                cereShopDestroyTickets.setPartnerOrderId(partnerOrderId);
                cereShopDestroyTickets.setTickets(String.valueOf(tickets));
                cereShopDestroyTicketsDao.insertSelective(cereShopDestroyTickets);
                return result;

                //...判断购买数量是否小于核销数量，如果小于核销数量则返回错误。
//                if (number<tickets) {
//                    System.out.println("核销数量不能大于购买数量,剩余可用数" + number);
//                    responseHead.setRes_code("5005");
//                    responseHead.setRes_msg("核销数量不能大于购买数量,剩余可用数" + number);
//                    responseHead.setTimestamp(millis);
//                    result.setResponseHead(responseHead);
//                    buffer.append("{");
//                    buffer.append("responseHead:{");
//                    buffer.append("res_code:" + responseHead.getRes_code() + ",");
//                    buffer.append("res_msg:" + responseHead.getRes_msg() + ",");
//                    buffer.append("timestamp:" + responseHead.getTimestamp() + "}");
//                    buffer.append("}");
//                    String toString = buffer.toString();
//                    try {
//                        String message = encrypt(toString, user_key);
//                        result.setResponseBody(message);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    return result;
//                }
//                if (number == 1){
                        //...修改订单状态为已完成
//                        cereShopOrderDAO.updateByOrderForMid(orderSerialId);
//                        responseHead.setRes_code("1000");
//                        responseHead.setRes_msg("操作成功");
//                        responseHead.setTimestamp(millis);
//                        result.setResponseHead(responseHead);
//                        buffer.append("{");
//                        buffer.append("responseHead:{");
//                        buffer.append("res_code:").append(responseHead.getRes_code()).append(",");
//                        buffer.append("res_msg:").append(responseHead.getRes_msg()).append(",");
//                        buffer.append("timestamp:").append(responseHead.getTimestamp()).append("}");
//                        buffer.append("}");
//                        String toString = buffer.toString();
//                        try {
//                            String message = encrypt(toString, user_key);
//                            result.setResponseBody(message);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//
//
//                        //核销完成后添加记录
//                        //添加数据
//                        cereShopDestroyTickets.setCounsumeDate(consumeDate);
//                        cereShopDestroyTickets.setOrderSerialld(orderSerialId);
//                        cereShopDestroyTickets.setTotalCheckCount(totalCheckCount);
//                        cereShopDestroyTickets.setPartnerOrderId(partnerOrderId);
//                        cereShopDestroyTickets.setTickets(String.valueOf(tickets));
//                        cereShopDestroyTicketsDao.insertSelective(cereShopDestroyTickets);
//                }else {
                    //...判断购买数量是否小于核销数量，如果小于核销数量则返回错误。
//                    if (number<tickets){
//                        responseHead.setRes_code("5005");
//                        responseHead.setRes_msg("核销数量不能大于购买数量");
//                        responseHead.setTimestamp(millis);
//                        result.setResponseHead(responseHead);
//                        buffer.append("{");
//                        buffer.append("responseHead:{");
//                        buffer.append("res_code:" + responseHead.getRes_code() + ",");
//                        buffer.append("res_msg:" + responseHead.getRes_msg() + ",");
//                        buffer.append("timestamp:" + responseHead.getTimestamp() + "}");
//                        buffer.append("}");
//                        String toString = buffer.toString();
//                        try {
//                            String message = encrypt(toString, user_key);
//                            result.setResponseBody(message);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        return result;
//                    }else {
//                        //...如果购买数量大于核销数量则减去此次核销数量
//                        BigDecimal bigDecimal = new BigDecimal(number);
//                        BigDecimal subtract = bigDecimal.subtract(new BigDecimal(tickets));
//                        int value = subtract.intValue();
//                        //...然后修改数据库购买数量
//                        cereOrderProductDAO.updateNumberBytickets(value, cereShopOrder.getOrderId());
//                        responseHead.setRes_code("1000");
//                        responseHead.setRes_msg("核销成功");
//                        responseHead.setTimestamp(millis);
//                        result.setResponseHead(responseHead);
//                        buffer.append("{");
//                        buffer.append("responseHead:{");
//                        buffer.append("res_code:" + responseHead.getRes_code() + ",");
//                        buffer.append("res_msg:" + responseHead.getRes_msg() + ",");
//                        buffer.append("timestamp:" + responseHead.getTimestamp() + "}");
//                        buffer.append("}");
//                        String toString = buffer.toString();
//                        //...核销成功后需要添加一则记录
//                        //核销完成后添加记录
//                        //添加数据
//                        cereShopDestroyTickets.setCounsumeDate(consumeDate);
//                        cereShopDestroyTickets.setOrderSerialld(orderSerialId);
//                        cereShopDestroyTickets.setTotalCheckCount(totalCheckCount);
//                        cereShopDestroyTickets.setPartnerOrderId(partnerOrderId);
//                        cereShopDestroyTickets.setTickets(String.valueOf(tickets));
//                        cereShopDestroyTicketsDao.insertSelective(cereShopDestroyTickets);
//                        //...修改订单状态为已完成
//                        cereShopOrderDAO.updateByOrderForMid(orderSerialId);
//                        try {
//                            String message = encrypt(toString, user_key);
//                            result.setResponseBody(message);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        return result;
//                    }
//                }
            } else {
                     responseHead.setRes_code("5004");
                     responseHead.setRes_msg("数据出错或为空");
                     responseHead.setTimestamp(millis);
                     result.setResponseHead(responseHead);
                     buffer.append("{");
                     buffer.append("responseHead:{");
                     buffer.append("res_code:" + responseHead.getRes_code() + ",");
                     buffer.append("res_msg:" + responseHead.getRes_msg() + ",");
                     buffer.append("timestamp:" + responseHead.getTimestamp() + "}");
                     buffer.append("}");
                     String toString = buffer.toString();
                     try {
                         String message = encrypt(toString, user_key);
                         result.setResponseBody(message);
                     } catch (Exception e) {
                         e.printStackTrace();
                     }
            }
            return result;
        } else {
             ResponseHead responseHead = new ResponseHead();
             responseHead.setRes_code("5003");
             responseHead.setRes_msg("签名验证失败");
             responseHead.setTimestamp(millis);
             result.setResponseHead(responseHead);
             buffer.append("{");
             buffer.append("responseHead:{");
             buffer.append("res_code:" + responseHead.getRes_code() + ",");
             buffer.append("res_msg:" + responseHead.getRes_msg() + ",");
             buffer.append("timestamp:" + responseHead.getTimestamp() + "}");
             buffer.append("}");
             String toString = buffer.toString();
             try {
                 String message = encrypt(toString, user_key);
                 result.setResponseBody(message);
             } catch (Exception e) {
                 e.printStackTrace();
             }
             return result;
        }
    }









//=======================================================================================================================================================================

    /**
     * Description 根据键值进行加密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8));
        return new BASE64Encoder().encode(bt);
    }

    /**
     * Description 根据键值进行解密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws Exception {
        if (data == null) {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf, key.getBytes("UTF-8"));
        return new String(bt, "UTF-8");
    }


    /**
     * Description 根据键值进行加密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    public static String getMD5(String content) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            md.update(content.getBytes());
            byte[] bytes = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                String str = Integer.toHexString(b & 0xFF);
                if (str.length() == 1) {
                    sb.append("0");
                }
                sb.append(str);
            }
            result = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Description 根据键值进行解密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

}
